/*
 * FixedSizeRegisterSequentialFile.h
 *
 *  Created on: Oct 17, 2012
 *      Author: m
 *
 *  Description: Archivo de Acceso Secuencial de Registros de tamaño fijo con buffers de
 *      lectura y escritura independientes. Solo permite leer registros y escribir
 *      nuevos registros, no permite borrar ni modificar ninguno de ellos.
 *
 */

#ifndef FIXEDSIZEREGISTERSECUENTIALFILE_H_
#define FIXEDSIZEREGISTERSECUENTIALFILE_H_

#include <fstream>
#include <memory>
#include <cassert>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <cstring>
#include "physical_layer_commons.h"

#ifndef NDEBUG

#include <cerrno>

#endif

namespace physical
{

class FixedSizeRegisterSequentialFile
{
private:
    std::fstream m_registerSource;
    size_t m_registerSize;
    size_t m_readBufferSize;
    size_t m_writeBufferSize;
    UP_byteStream m_readBuffer;
    UP_byteStream m_writeBuffer;
    byte* m_currentReadBufferPosition;
    byte* m_currentWriteBufferPosition;
    size_t m_readBufferRegisterCount;
    size_t m_writeBufferRegisterCount;

    static const openmode defaulOpenmode;

#ifndef NDEBUG

public:
    int lecturas;
    int escrituras;

#endif

public:
    FixedSizeRegisterSequentialFile( size_t registerSize,
            const char filename[] = NULL, openmode mode = defaulOpenmode,
            size_t readBufferSize = 1, size_t writeBufferSize = 1 );

    virtual ~FixedSizeRegisterSequentialFile();

    size_t readRegister( byte* registerBuffer );
    void writeRegister( const byteStream newRegister );
    size_t getRegisterSize();
    bool eof();
    void open( const char filename[], openmode mode = defaulOpenmode );
    void close();

private:
    bool readFromBuffer( byte* registerBuffer );
    void loadReadBuffer();
    void writeToBuffer( const byteStream registerBuffer );
    void flushWriteBuffer();
    void initializeBuffers();
    bool writeBufferIsFull();
};

}
#endif /* FIXEDSIZEREGISTERSECUENTIALFILE_H_ */
